<?php
/*
 * Summary : Created By Avik on 10th April,2010
 * Version : 1.0
 * Contents: This file is called when visitor fill up business listing form and click on save.
 * 			 Images are saved in upload/ folder.
 * 			 addslashes is used before saving this.
 * 			 SMTP mail support will be done. It is done so that when ever a listing is added a mail generates to the ADMIN.
 * 			 db-config.php file is included for database configuration.
 * 
 * Chnages: Multiple Categoty added.
 */

//#########INCLUDE FILES########

include_once 'conf/db-config.php';
include_once 'conf/error.php';
include_once 'submitemail.php';
include_once 'imageResize.php';
include_once("ImageResizeFactory.php");
//##############################

// GET DATA FROM POST VALUE
//===========================================================================


if($_REQUEST['action']=="editSave")
{
	$id = $_REQUEST['id'];
	$storedOneEdit = $_REQUEST['hdnImagePath'];
	$storedTwoEdit = $_REQUEST['hdnImagePath2'];
	$storedThreeEdit = $_REQUEST['hdnImagePath3'];
	$storedFourEdit = $_REQUEST['hdnImagePath4'];
	$storedFiveEdit = $_REQUEST['hdnImagePath5'];
	$barCodeImageEdit = $_REQUEST['hdnBarCodeImagePath'];
	//unlink($_REQUEST['hdnImagePath']);
	mysql_query("DELETE FROM tbl_globaltodo_listings WHERE id=".$id);
	
}

$businessCategory = array();
$city = addslashes($_POST['city']);
$businessCategory = $_POST['businessCategory'];
$businessTitle = str_replace("&","&amp;",addslashes($_POST['listingTitle']));
$businessDesc = addslashes(str_replace("&","&amp;",$_POST['businessDesc']));
$businessShortSummary = addslashes(str_replace("&","&amp;",$_POST['shortSummary']));
$phoneNumber =$_POST['phone'];
$streetAddress = addslashes(str_replace("&","&amp;",$_POST['streetAddress']));
$emailId = $_POST['email'];
$websiteAddress = $_POST['website'];
$audioUrl = $_POST['audioURL'];
$videoUrl = str_replace("&","&amp;",$_POST['videoURL']);
$salesRepresentatives = addslashes($_POST['salesRep']);
$stateProvince = addslashes($_POST['state']);
$zipCode = addslashes($_POST['zipCode']);
$tollfree = $_POST['tollfree'];
$fax = $_POST['fax'];
//$salesRep = $_POST['salesRep'];


//============================================================================

//Upload Image One (Logo)
//============================================================================
//print_r($_FILES["upload1"]);
if ($_FILES["upload1"]["error"] > 0)
  {
    //echo "Return Code: " . $_FILES["upload1"]["error"] . "<br />";
  }
  else
  {
    if (file_exists("upload/" . $_FILES["upload1"]["name"]))
    {
      //echo $_FILES["upload1"]["name"] . " already exists. ";
    }
    else
    {
      	$file1 = $_FILES["upload1"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file1, $extension);
 		$timestamp = time();
 		srand ((double) microtime( )*1000000);
		$random_number = rand( );
		//echo "$random_number";
		$newName = $timestamp.$random_number.".".$extension[2];
		
	    move_uploaded_file($_FILES["upload1"]["tmp_name"],
	    "upload/" . $file1);
	//################################################################
	    
	$size = getimagesize("upload/".$_FILES["upload1"]["name"]); 
	$width1 = $size[0];
	$height1 = $size[1];
	if($width1 > 600)
	{
		$width1 = ($width1*0.50);
	}  
	if($height1 > 500)
	{
		$height1 = ($height1*0.50);
	} 
	if($width1==0) $width1=500;
	if($height1==0) $height1=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName1 = $_FILES['upload1']['name'];
	$extension1 = pathinfo($_FILES['upload1']['name']);
	$extension1 = $extension1["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension1) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['upload1']['tmp_name'])) {
				copy($_FILES['upload1']['tmp_name'], "upload/" . $uploadedFileName1);
			}
		}
	}
	else
	{
		$error = "Files with .$extension1 extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile1 = "upload/" . $uploadedFileName1;
		$destFile1 = "upload/" . $uploadedFileName1;
		$destFile1_1 =  $srcFile1;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile1, $destFile1, $width1, $height1);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile1);
	}
	    
	//##################################################################
	    $storedOne = $destFile1_1;
	    //print $storedOne;
    }
  }
//==============================================================================
  
// Upload Extra Image One (Upload 2)
//==============================================================================
  if ($_FILES["upload2"]["error"] > 0)
  {
    //echo "Return Code: " . $_FILES["upload2"]["error"] . "<br />";
  }
  else
  {
  	//print_r($_FILES["upload2"]);
    if (file_exists("upload/" . $_FILES["upload2"]["name"]))
    {
      //echo $_FILES["upload2"]["name"] . " already exists. ";
    }
    else
    {
      	$file2 = $_FILES["upload2"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file2, $extension);
 		$timestamp = time(); 
 		srand ((double) microtime( )*2000000);
		$random_number2 = rand( );
		$newName = $timestamp.$random_number2.".".$extension[2];
		
	    move_uploaded_file($_FILES["upload2"]["tmp_name"],
	    "upload/" . $file2);
	    //################################################################
	    
	$size = getimagesize("upload/".$_FILES["upload2"]["name"]); 
	$width2 = $size[0];
	$height2 = $size[1];
	if($width2 > 600)
	{
		$width2 = ($width2*0.50);
	}  
	if($height2 > 500)
	{
		$height2 = ($height2*0.50);
	} 
	if($width2==0) $width2=500;
	if($height2==0) $height2=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName2 = $_FILES['upload2']['name'];
	$extension2 = pathinfo($_FILES['upload2']['name']);
	$extension2 = $extension2["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension2) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['upload2']['tmp_name'])) {
				copy($_FILES['upload2']['tmp_name'], "upload/" . $uploadedFileName2);
			}
		}
	}
	else
	{
		$error = "Files with .$extension2 extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile2 = "upload/" . $uploadedFileName2;
		$destFile2 = "upload/" . $uploadedFileName2;
		$destFile2_1 =  $srcFile2;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile2, $destFile2, $width2, $height2);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile2);
	}
	    
	//##################################################################
	    $storedTwo = $destFile2_1;
    }
  }
//===============================================================================

//Upload Extra Image Two (Upload 3)
//===============================================================================
  if ($_FILES["upload3"]["error"] > 0)
  {
    //echo "Return Code: " . $_FILES["upload3"]["error"] . "<br />";
  }
  else
  {
    if (file_exists("upload/" . $_FILES["upload3"]["name"]))
    {
      //echo $_FILES["upload3"]["name"] . " already exists. ";
    }
    else
    {
      	$file3 = $_FILES["upload3"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file3, $extension);
 		$timestamp = time(); 
 		srand ((double) microtime( )*3000000);
		$random_number3 = rand( );
		$newName = $timestamp.$random_number3.".".$extension[2];
		
	    move_uploaded_file($_FILES["upload3"]["tmp_name"],
	    "upload/" . $file3);
	    //################################################################
	    
	$size = getimagesize("upload/".$_FILES["upload3"]["name"]); 
	$width3 = $size[0];
	$height3 = $size[1];
	if($width3 > 600)
	{
		$width3 = ($width3*0.50);
	}  
	if($height3 > 500)
	{
		$height3 = ($height3*0.50);
	} 
	if($width3==0) $width3=500;
	if($height3==0) $height3=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName3 = $_FILES['upload3']['name'];
	$extension3 = pathinfo($_FILES['upload3']['name']);
	$extension3 = $extension3["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension3) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['upload3']['tmp_name'])) {
				copy($_FILES['upload3']['tmp_name'], "upload/" . $uploadedFileName3);
			}
		}
	}
	else
	{
		$error = "Files with .$extension3 extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile3 = "upload/" . $uploadedFileName3;
		$destFile3 = "upload/" . $uploadedFileName3;
		$destFile3_1 =  $srcFile3;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile3, $destFile3, $width3, $height3);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile3);
	}
	    
	//##################################################################
	    $storedThree = $destFile3_1;
    }
  }
//================================================================================

//Upload Extra Image Three (Upload 4)
//===============================================================================
  if ($_FILES["upload4"]["error"] > 0)
  {
    //echo "Return Code: " . $_FILES["upload4"]["error"] . "<br />";
  }
  else
  {
    if (file_exists("upload/" . $_FILES["upload4"]["name"]))
    {
     //echo $_FILES["upload4"]["name"] . " already exists. ";
    }
    else
    {
      	$file4 = $_FILES["upload4"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file4, $extension);
 		srand ((double) microtime( )*4000000);
		$random_number4 = rand( );
		$newName = $timestamp.$random_number4.".".$extension[2];
		
	    move_uploaded_file($_FILES["upload4"]["tmp_name"],
	    "upload/" . $file4);
	     //################################################################
	    
	$size = getimagesize("upload/".$_FILES["upload4"]["name"]); 
	$width4 = $size[0];
	$height4 = $size[1];
	if($width4 > 600)
	{
		$width4 = ($width4*0.50);
	}  
	if($height4 > 500)
	{
		$height4 = ($height4*0.50);
	} 
	if($width4==0) $width4=500;
	if($height4==0) $height4=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName4 = $_FILES['upload4']['name'];
	$extension4 = pathinfo($_FILES['upload4']['name']);
	$extension4 = $extension4["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension4) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['upload4']['tmp_name'])) {
				copy($_FILES['upload4']['tmp_name'], "upload/" . $uploadedFileName4);
			}
		}
	}
	else
	{
		$error = "Files with .$extension4 extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile4 = "upload/" . $uploadedFileName4;
		$destFile4 = "upload/" . $uploadedFileName4;
		$destFile4_1 =  $srcFile4;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile4, $destFile4, $width, $height);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile4);
	}
	    
	//##################################################################
	    $storedFour = $destFile4_1;
    }
  }
//================================================================================

//Upload Extra Image Four (Upload 5)
//===============================================================================
  if ($_FILES["upload5"]["error"] > 0)
  {
   // echo "Return Code: " . $_FILES["upload5"]["error"] . "<br />";
  }
  else
  {
    if (file_exists("upload/" . $_FILES["upload5"]["name"]))
    {
      //echo $_FILES["upload5"]["name"] . " already exists. ";
    }
    else
    {
      	$file5 = $_FILES["upload5"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file5, $extension);
 		$timestamp = time();
 		srand ((double) microtime( )*5000000);
		$random_number5 = rand( );
		$newName = $timestamp.$random_number5.".".$extension[2];
		
	    move_uploaded_file($_FILES["upload5"]["tmp_name"],
	    "upload/" . $file5);
	     //################################################################
	    
	$size = getimagesize("upload/".$_FILES["upload5"]["name"]); 
	$width5 = $size[0];
	$height5 = $size[1];
	if($width5 > 600)
	{
		$width5 = ($width5*0.50);
	}  
	if($height5 > 500)
	{
		$height5 = ($height5*0.50);
	} 
	if($width5==0) $width5=500;
	if($height5==0) $height5=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName5 = $_FILES['upload5']['name'];
	$extension5 = pathinfo($_FILES['upload5']['name']);
	$extension5 = $extension5["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension5) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['upload5']['tmp_name'])) {
				copy($_FILES['upload5']['tmp_name'], "upload/" . $uploadedFileName5);
			}
		}
	}
	else
	{
		$error = "Files with .$extension5 extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile5 = "upload/" . $uploadedFileName5;
		$destFile5 = "upload/" . $uploadedFileName5;
		$destFile5_1 =  $srcFile5;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile5, $destFile5, $width5, $height5);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile5);
	}
	    
	//##################################################################
	    $storedFive = $destFile5_1;
    }
  }
//================================================================================
  //Upload BAR CODE IMAGE 
//===============================================================================
  if ($_FILES["uploadBarCode"]["error"] > 0)
  {
  }
  else
  {
  	
    if (file_exists("upload/" . $_FILES["uploadBarCode"]["name"]))
    {
      //echo $_FILES["upload5"]["name"] . " already exists. ";
    }
    else
    {
      	$file6 = $_FILES["uploadBarCode"]["name"];
 		preg_match("/([a-zA-Z0-9_-]+).([a-zA-Z0-9]+)/", $file6, $extension);
 		$timestamp = time();
 		srand ((double) microtime( )*6000000);
		$random_number6 = rand( ); 
		$newName = $timestamp.$random_number6.".".$extension[2];
		
	    move_uploaded_file($_FILES["uploadBarCode"]["tmp_name"],
	    "upload/" . $file6);
	     //################################################################
	    
	$size = getimagesize("upload/".$_FILES["uploadBarCode"]["name"]); 
	$width = $size[0];
	$height = $size[1];
	if($width > 600)
	{
		$width = ($width*0.50);
	}  
	if($height > 500)
	{
		$height = ($height*0.50);
	} 
	if($width==0) $width=500;
	if($height==0) $height=350;
    $allowedExtensions = array("jpg", "JPG", "JPEG", "png", "PNG");
	$uploadedFileName = $_FILES['uploadBarCode']['name'];
	$extension = pathinfo($_FILES['uploadBarCode']['name']);
	$extension = $extension["extension"];
	foreach($allowedExtensions as $key=>$ext) {
		if(strcasecmp($ext, $extension) == 0)
		{
			$boolValidExt = true;
			break;
		}
	}
	if($boolValidExt) {
		if(empty($error)) {
			if(is_uploaded_file($_FILES['uploadBarCode']['tmp_name'])) {
				copy($_FILES['uploadBarCode']['tmp_name'], "upload/" . $uploadedFileName);
			}
		}
	}
	else
	{
		$error = "Files with .$extension extensions are not allowed";
	}
	if(empty($error))
	{
		$srcFile6 = "upload/" . $uploadedFileName;
		$destFile6 = "upload/" . $uploadedFileName;
		$destFile6_1 =  $srcFile6;
		// Instantiate the correct object depending on type of image i.e jpg or png
		$objResize = ImageResizeFactory::getInstanceOf($srcFile6, $destFile6, $width, $height);
		// Call the method to resize the image
		$objResize->getResizedImage();
		//unlink($srcFile6);
	}
	    
	//##################################################################
	    $barCodeImage = $destFile6_1;
    }
  }
  //=================================================
  
  //==================================================
  if(strlen($storedOne)==0)
  {
  	$storedOne = $storedOneEdit;
  }
   if(strlen($storedTwo)==0)
  {
  	$storedTwo = $storedTwoEdit;
  }
   if(strlen($storedThree)==0)
  {
  	$storedThree = $storedThreeEdit;
  }
   if(strlen($storedFour)==0)
  {
  	$storedFour = $storedFourEdit;
  }
   if(strlen($storedFive)==0)
  {
  	$storedFive = $storedFiveEdit;
  }
  if(strlen($barCodeImage)==0)
  {
  	$barCodeImage = $barCodeImageEdit;
  }
  
//==========================INSERT DATA QUERY=====================================
 if(is_array($businessCategory) && count($businessCategory)>0)
  {
  	foreach ($businessCategory as $category)
  	{
  	  $category = str_replace("&","&amp;",$category);
	  $insert = "INSERT INTO tbl_globaltodo_listings (`sales_rep`,`fax_number`,`tollfree_number`,`zipcode`,`city`,`category`,`business_title`,`business_desc`,`business_summary`, ";
	  $insert .=" `phone_number`, `street_address` , `email_address`, `website_address`, `audio_url`, `video_url`, `business_logo`, `image_1`, `image_2`, `image_3`, ";
	  $insert .=" `image_4`, `is_approved`,`state`,`barcode_image`) VALUES (";
	  $insert .=" '". $salesRepresentatives ."' ,'". $fax ."' , '".$tollfree."' ,";
	  $insert .=" '".$zipCode."' , '".$city."' , '".$category."', '".$businessTitle."', '".$businessDesc."', '".$businessShortSummary."', ";
	  $insert .=" '".$phoneNumber."' , '".$streetAddress."' , '".$emailId."' , '".$websiteAddress."' , '".$audioUrl."' , '".$videoUrl."',  ";
	  $insert .=" '".$storedOne."' , '".$storedTwo."' , '".$storedThree."' , '".$storedFour."' , '".$storedFive."' , 'b' ,'".$stateProvince."','".$barCodeImage."')";
	  $run = mysql_query($insert);
	  if($run)
	  {
	  	$success = "OK";
	  }
  	}
  }
  else
  {
  	
  	  $category = str_replace("&","&amp;",$category);
  	  $insert = "INSERT INTO tbl_globaltodo_listings (`sales_rep`,`fax_number`,`tollfree_number`,`zipcode`,`city`,`category`,`business_title`,`business_desc`,`business_summary`, ";
	  $insert .=" `phone_number`, `street_address` , `email_address`, `website_address`, `audio_url`, `video_url`, `business_logo`, `image_1`, `image_2`, `image_3`, ";
	  $insert .=" `image_4`, `is_approved`,`state`,`barcode_image`) VALUES (";
	  $insert .=" '". $salesRepresentatives ."' ,'". $fax ."' , '".$tollfree."' ,";
	  $insert .=" '".$zipCode."' , '".$city."' , '".$category."', '".$businessTitle."', '".$businessDesc."', '".$businessShortSummary."', ";
	  $insert .=" '".$phoneNumber."' , '".$streetAddress."' , '".$emailId."' , '".$websiteAddress."' , '".$audioUrl."' , '".$videoUrl."',  ";
	  $insert .=" '".$storedOne."' , '".$storedTwo."' , '".$storedThree."' , '".$storedFour."' , '".$storedFive."' , 'b' ,'".$stateProvince."','".$barCodeImage."')";
	 
	  $run = mysql_query($insert);
	  if($run)
	  {
	  	$success = "OK";
	  }
  }
//================================================================================
  
//=========================MYSQL DATA CALL & RESULT ==============================
  if($success=="OK" && $_REQUEST['action']!="editSave")
  {
  	$message = "success";
  }
  else
  {
  	
  }
//================================================================================  
  //======================PAGE REDIRECTION========================================
  if($message=="success")
  {
  	if($_REQUEST['action']=="editSave")
  	{
  	?>
	  	<script type="text/javascript">
	  	window.open('admin/new-listing.php','_self');
	  	</script>
  	<?php 
  	}
  	else
  	{
  		?>
  		<script type="text/javascript">
	  	window.open('../thankyou.html','_self');
	  	</script>
  		<?php 
  	}
  }
  else
  {
  	if($_REQUEST['action']=="editSave")
  	{
  	?>
	  	<script type="text/javascript">
	  	window.open('admin/new-listing.php','_self');
	  	</script>
  	<?php 
  	}
  	else
  	{
  		?>
  		<script type="text/javascript">
	  	window.open('../thankyou.html','_self');
	  	</script>
  		<?php 
  	}
  }
  
  //==============================================================================

